import { Tween } from 'cc';
import { _decorator, Component, Node, Label, tween, view, UITransform, Vec3, SpriteAtlas, SpriteFrame, Sprite, Button, ScrollView, find, math, RichText, EventTouch, WebView } from 'cc';
import { App } from '../../App';
import { EventConst } from '../../common/Common';
import CommConst from '../../const/CommConst';
import wsTool from '../../net/ws';
import { PD } from '../../player/PlayerData';
import { LoadMg } from '../../tools/LoadMg';
import { setLanguagePopuUp, showTip } from '../../tools/PopuUp';
import { TipMg } from '../../tools/TipMg';
import UtilTool from '../../tools/UtilTool';
import ScrollHelper from '../ScrollHelper';
const { ccclass, property } = _decorator;

// 记录界面
@ccclass('LBRecordPanel')
export class LBRecordPanel extends Component {
    @property(Node)
    contentNode: Node = null;

    @property(Node)
    scrollNode: Node = null;

    private itemNum = 5
    // [listData]列表数据  [isLoading]是否加载中 [loadOver]是否加载结束(如果没有新的数据则认为是加载结束) [currPage]当前已经请求的第几页的数据 [dataDirty]是否需要重新拉取数据 
    private configData = {listData : [], isLoading : false, loadOver : false, currPage : 0, dataDirty : true, pageSize : 30}
    // 记录数据
    private recodeData = null
    private parentObj = null

    onLoad() {
      UtilTool.setScreen(this.node)
    }

    start() {
        this.node.getComponent(UITransform).setContentSize(view.getVisibleSize())
        UtilTool.setSize(this.scrollNode, 3, [0, 2])
        UtilTool.setSize(this.scrollNode.getChildByName("view"), 3, [0, 2])
        UtilTool.setSize(find("view/content",this.scrollNode), 3, [0, 2])
        UtilTool.setPos(this.scrollNode, [0, 1])

        find("Btn_close",this.contentNode).active = false
        find("SpriteSplash-001",this.node).active = false

        let H = UtilTool.getGapSize().height*2
        if (H>0) {
            this.itemNum = this.itemNum + Math.ceil(H/544)
        }

        this.reqData()
    }

    setData(obj) {
        this.parentObj = obj
    }

    /**
     * 请求数据
     */
    reqData(pInit=true) {
        this.configData.isLoading = true
        
        wsTool.send({"msgCode":CommConst.Req_BETLIST, "page":this.configData.currPage, "pageSize":this.configData.pageSize, "findCurrentPeriod":true})
        .then(res =>{
            // if (res?.result == 0) {
                // 数据回来
                // let res = {list:[]}
                this.recodeData= res
                this.configData.currPage = this.configData.currPage + 1
                this.configData.isLoading = false
                /* res.list = [{"blockId": 17498394,"createTime": 1686991250000,"hashId": "werafsafdsfdgfasfdsgsdo0e51","id": 21,"nums": "1,2,3","period": "2306170146","rewardTime": 1686991496000,"status": 2,"type": 4,"userId": 200002,"value": 102},{"blockId": 17498394,"createTime": 1686991250000,"hashId": "werafsafdsfdgfasfdsgsdo0e52","id": 21,"nums": "1,2,3","period": "2306170146","rewardTime": 1686991496000,"status": 2,"type": 4,"userId": 200002,"value": 102},{"blockId": 17498394,"createTime": 1686991250000,"hashId": "werafsafdsfdgfasfdsgsdo0egfdhfgjfgjjfghdjdghfjghdjhygkjhuyoiuphgjdhgdjgh52000","id": 21,"nums": "1,2,3","period": "2306170146","rewardTime": 1686991496000,"status": 2,"type": 4,"userId": 200002,"value": 102},{"blockId": 17498394,"createTime": 1686991250000,"hashId": "werafsafdsfdgfasfdsgsdo0e53","id": 21,"nums": "1,2,3","period": "2306170146","rewardTime": 1686991496000,"status": 2,"type": 4,"userId": 200002,"value": 102},{"blockId": 17498394,"createTime": 1686991250000,"hashId": "werafsafdsfdgfasfdsgsdo0e54","id": 21,"nums": "1,2,3","period": "2306170146","rewardTime": 1686991496000,"status": 2,"type": 4,"userId": 200002,"value": 102},{"blockId": 17498394,"createTime": 1686991250000,"hashId": "werafsafdsfdgfasfdsgsdo0e55","id": 21,"nums": "1,2,3","period": "2306170146","rewardTime": 1686991496000,"status": 2,"type": 4,"userId": 200002,"value": 102},{"blockId": 17498394,"createTime": 1686991250000,"hashId": "werafsafdsfdgfasfdsgsdo0e56","id": 21,"nums": "1,2,3","period": "2306170146","rewardTime": 1686991496000,"status": 2,"type": 4,"userId": 200002,"value": 102},{"blockId": 17498394,"createTime": 1686991250000,"hashId": "werafsafdsfdgfasfdsgsdo0e57","id": 21,"nums": "1,2,3","period": "2306170146","rewardTime": 1686991496000,"status": 2,"type": 4,"userId": 200002,"value": 102}]   // 测试数据 */
                res.list.forEach(element => {
                    this.configData.listData.push(element)
                });
                if (res.list==null || res.list.length < this.configData.pageSize) {
                    this.configData.loadOver = true
                }
                if (this.configData.currPage==1) {
                    this.setDJSTime()
                }
                // 最新请求的数据列表大于0，才会去刷新界面
                if (res.list.length>0) {
                    let param = {
                        init:pInit, 
                        data:this.configData.listData, 
                        itemNum:this.itemNum, 
                        itemFun: (obj,idx,objIdx)=>{
                            this.refreshItem(obj,idx,objIdx)
                        },
                        endFun:()=>{
                            this.OnScrollEnd()
                        }
                    }
    
                    this.scrollNode.getComponent(ScrollHelper).setData(param)
                }

                if (this.configData.listData.length==0) {
                    showTip(App.language.getLanguageLab(54))
                    this.node.destroy()
                }
                else {
                    if (this.configData.currPage == 1) {
                        find("Btn_close",this.contentNode).active = true
                        find("SpriteSplash-001",this.node).active = true
                    }
                }
                
                
            // }
            // else{
            //     alert('获取数据失败')
            // } 
        })
    }

    /** 
     * 刷新数据
     * param obj item对象
     * param idx 实际的下标索引
     * param objIdx item本身的下标索引
    */
    refreshItem(obj,idx,objIdx) {
        if (this.configData.listData.length <= 0) {
            return
        }

        let periodLabel = find("bg/periodLabel", obj).getComponent(Label)   // 期号
        let numberLabel = find("bg/numberLabel", obj).getComponent(Label)   // 球号
        let betMoneyLabel = find("bg/coinSpr/betMoneyLabel", obj).getComponent(Label) // 下注的金币
        let btn_lookover = find("bg/btn_lookover", obj)    // 哈希值按钮
        let hash = find("bg/btn_lookover/hash", obj).getComponent(Label)     // 哈希值

        let waitNode = find("bg/waitNode", obj) // 等待开奖
        let failNode = find("bg/failNode", obj) // 未中奖
        let winNode = find("bg/winNode", obj)   // 中奖

        // 期数&球号&下注数
        let itemData = this.configData.listData[idx]
        obj.dataId = itemData.id

        periodLabel.string = App.language.getLanguageLab(14).replace("&", itemData.period)
        numberLabel.string = App.language.getLanguageLab(17) + itemData.nums
        betMoneyLabel.string = itemData.value

        // 哈希值
        if (itemData.hashId && itemData.hashId.length>6) {
            hash.string = UtilTool.getShortWalletAddr("0x" + itemData.hashId,4,4)  + App.language.getLanguageLab(18)
        }
        else{
            hash.string = ""
        }

        // 点击哈希值展示详情
        btn_lookover.off(Node.EventType.TOUCH_END)
        btn_lookover.on(Node.EventType.TOUCH_END,(event: EventTouch) =>{
            App.Audio.playOneShot("click")
            //https://cn.etherscan.com/tx/0xfff3abadb0a8eb5a58a895350f8cbc4c071b52edccaf12b15109a63d574fb1cc
            window.location.href = "https://etherscan.com/tx/" + "0x" + itemData.hashId
        },btn_lookover)

        // 未击打：status == 4 && hitStatus == 0
        // 击打失败： status == 4 && hitStatus == 2
        // 击打成功： status == 4 && hitStatus == 1
        // 击球倒计时： status == 1 && hitStatus== 0
        // 未中奖：status == 2
        // 等待开奖：status == 0
        // [status]状态 0未结算 1中奖 2未中奖 3已击球 4已结算      [hitStatus]击球状态 0未击球 1已进洞 2未进洞    
        waitNode.active = itemData.status==0
        failNode.active = itemData.status==2
        winNode.active = (itemData.status==1 || itemData.status==4)

        if (itemData.status == 0) {//等待开奖

        }
        else if (itemData.status == 2) {//未中奖
            let ballSpr = find("ballSpr", failNode)    // 球
            ballSpr.getComponent(Sprite).spriteFrame = this.parentObj.ballArr[parseInt(itemData.lotteryNum)]
        }
        else if (itemData.status==1 || itemData.status==4) {//中奖
            let statusBtn1 = find("status1", winNode)    // 状态按钮（击球倒计时）
            let statusBtn2 = find("status2", winNode)    // 状态按钮（击打成功）
            let statusBtn3 = find("status3", winNode)    // 状态按钮（击打失败）
            let statusBtn4 = find("status4", winNode)    // 状态按钮（未击打）
            statusBtn1.active = false
            statusBtn2.active = false
            statusBtn3.active = false
            statusBtn4.active = false

            let ball = find("ball", winNode)    // 球
            let winCoinLabel = find("winCoinLabel", winNode).getComponent(Label)    // 奖励
            ball.getComponent(Sprite).spriteFrame = this.parentObj.ballArr[parseInt(itemData.lotteryNum)]

            if (itemData.status==1 && itemData.hitStatus==0) { //击球倒计时
                winCoinLabel.string = itemData.value * this.recodeData.baseOdds + ""
                statusBtn1.active = true

                let timeLabel = find("timeLabel", statusBtn1).getComponent(Label)    // 球
                UtilTool.timeCountdown2(timeLabel, itemData.countdown, ()=>{

                })
                // 点击击球进游戏
                statusBtn1.off(Node.EventType.TOUCH_END)
                statusBtn1.on(Node.EventType.TOUCH_END,(event: EventTouch) =>{
                    App.Audio.playOneShot("click")
                    this.parentObj.enterGame()
                },statusBtn1)
            }
            else if (itemData.status==4 && itemData.hitStatus==0) {// 未击打
                winCoinLabel.string = itemData.reward + ""
                statusBtn4.active = true
            }
            else if (itemData.status==4 && itemData.hitStatus==1) {// 击打成功
                winCoinLabel.string = itemData.reward + ""
                statusBtn2.active = true
            }
            else if (itemData.status==4 && itemData.hitStatus==2) {// 击打失败
                winCoinLabel.string = itemData.reward + ""
                statusBtn3.active = true
            }
        }
        else {
            
        }
        
    }

    // 滚动视图滑到底部回调
    OnScrollEnd() {
        if (this.configData.isLoading) {
            return
        }
        if (this.configData.loadOver) {
            return
        }

        this.reqData(false)
    }

    /** 
     * 判断是否为击球倒计时状态，并且保存时间
      */
    setDJSTime() {
        let that = this
        let oneData = null
        let countdown = 0
        for (let i = 0; i < this.configData.listData.length; i++) {
            let data = this.configData.listData[i]
            if (data.status==1 && data.hitStatus==0) {
                oneData = data
                countdown = data.countdown
                break
            }
        }

        if (countdown<=0) {
            return
        }

        let stopDJS = function() {
            // 停止倒计时
            Tween.stopAllByTarget(that.node)
        }

        stopDJS()
        let embedTween = tween(this.node)
            .delay(1.0)
            .call(() => {
                countdown = countdown - 1
                
                if (countdown<0) {
                    stopDJS()
                    oneData.status = 4
                    oneData.hitStatus = 0
                    oneData.reward = oneData.value * that.recodeData.baseOdds
                    that.updateDJSItemLJ(oneData)
                    
                    return
                }
                oneData.countdown = countdown
            })
        tween(this.node)
            .repeatForever(embedTween)
            .start()
    }

    // 更新倒计时那条记录
    updateDJSItemLJ(newData) {
        let idx = null
        // 刷新列表数据
        for (let i = 0; i < this.configData.listData.length; i++) {
            let oneData = this.configData.listData[i]
            if (oneData.id == newData.id) {
                idx = i
                break
            }
        }

        if (idx!=null) {
            // 刷新界面显示
            let itemsList = this.scrollNode.getComponent(ScrollHelper).itemsList
            for (let i = 0; i < itemsList.length; i++) {
                let obj = itemsList[i]
                if (obj.dataId == newData.id) {
                    this.refreshItem(obj, idx, i)
                    break
                }
            }
        }
    }

    /** 
     * 关闭
      */
    clickClose() {
        App.Audio.playOneShot("click")
        this.node.destroy();
    }
    
}

